import Vue from "vue";
import VueRouter from "vue-router";

//方法
import { getToken } from "@/utils/storage";
import { Toast } from "vant";

// 一级路由
import Login from "@/views/Login";
import Register from "@/views/Register";
import Home from "@/views/Home";

// 二级路由
import List from "@/views/Home/List";
import News from "@/views/Home/News";
import My from "@/views/Home/My";

Vue.use(VueRouter);

const routes = [
  {
    path: "/login",
    component: Login,
  },
  {
    path: "/register",
    component: Register,
  },
  {
    path: "/",
    component: Home,
    redirect: "/home",
    children: [
      {
        path: "/home",
        component: Home,
      },
      {
        path: "/home/list",
        component: List,
      },
      {
        path: "/home/news",
        component: News,
      },
      {
        path: "/home/profile",
        component: My,
      },
    ],
  },
];

const router = new VueRouter({
  routes,
});

// 全局前置守卫：

const whiteList = ["/login", "/register"];

router.beforeEach((to, from, next) => {
  if (getToken()) {
    next();
  } else {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      Toast.fail("游客请先登录");
      next("/login");
    }
  }
});

export default router;
